class Upload < Tiddler

  DIRECTORY = 'public/uploaded'

  after_create :process
  after_destroy :cleanup

  def file_data=(file_data)
    @file_data = file_data
    write_attribute 'extension',
                    file_data.original_filename.split('.').last.downcase
  end
  
  def url
    path.sub(/^public/,'')
  end
  
  def thumbnail_url
    thumbnail_path.sub(/^public/,'')
  end
  
  def path(relative=false)
    if relative
      return "/" + File.join(DIRECTORY.split('/')[-1], "#{self.title.gsub(/\W/, '_')}.#{extension}")
    end
    #File.join(DIRECTORY, "#{self.id}-full.#{extension}")
    File.join(DIRECTORY, "#{self.title.gsub(/\W/, '_')}.#{extension}")
  end
  
  def thumbnail_path
    File.join(DIRECTORY, "#{self.id}-thumb.#{extension}")
  end


  #######
  private
  #######
	
  def process
    if @file_data
      create_directory
      cleanup
      save_fullsize
      #create_thumbnail
      @file_data = nil
    end
  end

   
  def save_fullsize
    File.open(path,'wb') do |file|
      file.puts @file_data.read
    end
  end
  
  def create_thumbnail
    img = Magick::Image.read(path).first
    thumbnail = img.thumbnail(*THUMB_MAX_SIZE)
    thumbnail.write thumbnail_path	  
  end
  
  def create_directory
    FileUtils.mkdir_p DIRECTORY
  end
  
  def cleanup
    Dir[File.join(DIRECTORY, "#{self.id}-*")].each do |filename|
      File.unlink(filename) rescue nil
    end
  end

end
